package com.yifeng.repo.micro.service.server.engine.dal.log;

import com.alibaba.druid.filter.FilterChain;
import com.alibaba.druid.filter.logging.Slf4jLogFilter;
import com.alibaba.druid.proxy.jdbc.CallableStatementProxy;
import com.alibaba.druid.proxy.jdbc.PreparedStatementProxy;
import com.alibaba.druid.proxy.jdbc.ResultSetProxy;
import com.alibaba.druid.proxy.jdbc.StatementProxy;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;

/**
 * Created by daibing on 2023/3/31.
 */
@Slf4j
public class DruidSlf4jLogFilter extends Slf4jLogFilter {

    public DruidSlf4jLogFilter() {
        this.setStatementLogEnabled(true);
        this.setStatementExecutableSqlLogEnable(false);
        this.setStatementExecuteAfterLogEnabled(true);
        this.setStatementExecuteBatchAfterLogEnabled(true);
        this.setStatementExecuteQueryAfterLogEnabled(true);
        this.setStatementExecuteUpdateAfterLogEnabled(true);

        this.setResultSetLogEnabled(true);
        this.setResultSetNextAfterLogEnabled(false);
        this.setResultSetOpenAfterLogEnabled(false);
        this.setResultSetCloseAfterLogEnabled(true);
    }

    @Override
    public void resultSet_close(FilterChain chain, ResultSetProxy resultSet) throws SQLException {
        if (isResultSetCloseAfterLogEnabled()) {
            StringBuffer buf = new StringBuffer();
            buf.append("{conn-");
            buf.append(resultSet.getStatementProxy().getConnectionProxy().getId());
            buf.append(", ");
            buf.append(stmtId(resultSet));
            buf.append(", rs-");
            buf.append(resultSet.getId());
            buf.append(", FetchSize-");
            buf.append(resultSet.getFetchSize());
            buf.append(", FetchRowCount-");
            buf.append(resultSet.getFetchRowCount());
            buf.append("} closed");
            resultSetLog(buf.toString());
        }
        chain.resultSet_close(resultSet);
    }

    private String stmtId(ResultSetProxy resultSet) {
        return stmtId(resultSet.getStatementProxy());
    }

    private String stmtId(StatementProxy statement) {
        StringBuffer buf = new StringBuffer();
        if (statement instanceof CallableStatementProxy) {
            buf.append("cstmt-");
        } else if (statement instanceof PreparedStatementProxy) {
            buf.append("pstmt-");
        } else {
            buf.append("stmt-");
        }
        buf.append(statement.getId());

        return buf.toString();
    }
}
